package scanpackage.aspect;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CustomAspect {
    @Autowired
    private CacheManager cacheManager;

    @Pointcut(value = "@annotation(scanpackage.annotation.UseCache)")
    public void useCache()
    {

    }


    @Around(value= "useCache()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        Object[] args = point.getArgs();
        String queryArgs= (String) args[0];//如果这个是一个数据库查询，那么我们就假设他是一个select * from table的语句
        Cache cache = cacheManager.getCache("cacheTest");
        Element element = cache.get(queryArgs);
        if(element==null)
        {
            System.out.println("写入缓存");
            String proceed = (String) point.proceed();//返回结果
            Element putGreeting = new Element(args[0], proceed);
            cache.put(putGreeting);//写入到缓存中
            return proceed;
        }
        return element.getObjectValue().toString();
    }

}
